import React from 'react';
import { connect } from 'react-redux'
import { messages, deepCopy } from "share/common"
import moment from 'moment'
import TagSelect from 'ant-design-pro/lib/TagSelect'
import {
  Form, Modal, Collapse, Select, Button, Input, InputNumber, Spin, Menu, Dropdown, Icon, Row, Col,
  Popconfirm, Tag, Popover, DatePicker,
} from 'antd'
import { nodeTypes } from "components/simple-flow/node-list";
import { SelectDepOrPerson } from 'components/index'
import config from 'config'
const FormItem = Form.Item;
const Option = Select.Option;
const Panel = Collapse.Panel;
import workflowService from 'containers/setting/workflow/workflow.service'
import workflowUtil from 'containers/setting/new-workflow/utils'
import { chnNumChar, itineraryTypes } from 'containers/setting/new-workflow/utils'
import ListSearcher from 'components/list-searcher'
import ListSelector from 'components/list-selector'
import ExpenseTypeSelector from 'components/template/expense-type-selector'
import NewAddApproveRuleModal from 'containers/setting/new-workflow/setting/add-rule-modal'
class WorkflowConditionSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      basicInfo: {},
      loading: false,
      ruleApprovalNodeOID: '',
      selectApprovalRule: 5003,
      formInfo: {},
      ruleConditionList: [],
      ruleRoutes: [],
      ruleConditions: {},
      nowNode: {
        ruleConditionDTO: {
          symbol: 9020,
          ruleConditionDTOList: []
        },
      },
      symbolsType: [],
      conditionSymbol: 9020,
      conditionSymbolVisible: false,
      selectorLoading: false,
      selectorVisible: false,
      selectorData: [],
      selectorNowData: [],
      conditionOID: null,
      listSearcherVisible: false,
      listSelectorVisible: false,
      listSearcherParams: {},
      ruleDepth: 0,
      level: 0,
      ruleIndex: 0,
      symbolGroupVisible: false,
      outerVisible: false,
      isAddGroup: false,
      symbolTpye: 9020,
      singleExpense: false,//费用类型单选
      expenseTypeValue: [],
      expenseTypeVisible: false,
      //默认值showvalue
      expenseTypeList: [],
      //默认值showvalue
      copyNowNode: {},
    };
  }

  componentDidMount() {
    let { nowNode } = this.props.params;
    this.setState({
      priority: nowNode.priority,
      ruleRoutes: this.props.ruleRoutes,
      copyNowNode: deepCopy(nowNode)
    }, () => {
      if (!nowNode.ruleConditionDTO) {
        nowNode.ruleConditionDTO = {
          symbol: 9020,
          type: 2,
          ruleConditionDTOList: []
        }
      }
      this.setState({ nowNode, })
      this.getAllSymbolsType();
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.params.nowNode.ruleApprovalNodeOID !== this.state.nowNode.ruleApprovalNodeOID
      || (JSON.stringify(this.state.nowNode) !== JSON.stringify(nextProps.params.nowNode) )) {
      let { nowNode } =nextProps.params;
      this.setState({
        priority: nowNode.priority,
        ruleRoutes: nextProps.ruleRoutes,
        copyNowNode: deepCopy(nowNode)
      }, () => {
        if (!nowNode.ruleConditionDTO) {
          nowNode.ruleConditionDTO = {
            symbol: 9020,
            ruleConditionDTOList: []
          }
        }
        this.setState({ nowNode })
        this.getAllSymbolsType();
      })
    }
  }

  onCancel = () => {
    this.setState({
      symbolGroupVisible: false,
      conditionSymbolVisible: false,
      nowNode: this.state.copyNowNode
    }, () => {
      this.props.onSave(this.state.copyNowNode);
    })
  };

  //获取所有的条件操作符
  getAllSymbolsType = () => {
    return new Promise((resolve, reject) => {
      workflowService.getSymbolsType().then(res => {
        this.setState({ symbolsType: res.data });
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  };
  //修改条件设置的回调
  onChangeAttr = (value, attr) => {
    let { nowNode } = this.state;
    nowNode[attr] = value;
    this.setState({
      nowNode
    });
  };

  /**
   * index1当前优先级index
   * index2目标优先级index
   **/
  swapArray = (arr, index1, index2) => {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr.filter(item => {return item !== undefined});
  };

  getConditionlength = () => {
    let { chainInfo } = this.props.params;
    let { nowNode } = this.state;
    let tempNodes = JSON.parse(JSON.stringify(chainInfo.ruleApprovalNodes));
    let fromNodeOID = null;
    let sameSpanCondition = [];
    chainInfo.ruleApprovalRoutes.map(route => {
      if (route.to === nowNode.ruleApprovalNodeOID) {
        fromNodeOID = route.from;
      }
    });
    chainInfo.ruleApprovalRoutes.map(route => {
      if (fromNodeOID === route.from) {
        tempNodes.map(node => {
          if (route.to === node.ruleApprovalNodeOID) {
            sameSpanCondition.push(node);
          }
        })
      }
    });
    return sameSpanCondition.sort((a, b) => a.priority - b.priority);
  };

  handleChangeLevel = (e, attr) => {
    e = Number(e);
    let arr = [];
    let { copyNowNode } = this.state;
    let { ruleApprovalNodes }= this.props;
    this.onChangeAttr(e, attr);
    this.setState({ priority: e });
    if (e !== copyNowNode.priority) {
      if (e < copyNowNode.priority) {//提高优先级
        arr = this.swapArray(this.getConditionlength(), copyNowNode.priority - 1, e - 1).filter(item => {return item !== undefined});
        arr.map((item, index) => {
          //提高优先级
          item.priority = index + 1
        });
      } else {//降低优先级
        console.log(this.getConditionlength())
        arr = this.swapArray(this.getConditionlength(), copyNowNode.priority - 1, e - 1).filter(item => {return item !== undefined});
        arr.map((item, index) => {
          item.priority = index + 1
        });
      }
    }
    ruleApprovalNodes.map(node => {
      arr.map(item => {
        if (node.ruleApprovalNodeOID === item.ruleApprovalNodeOID) {
          node.priority = item.priority
        }
      })
    });
  };

  handleSave = () => {
    let { nowNode } = this.state;
    let copyNow = JSON.parse(JSON.stringify(nowNode))
    let saveAble = true; //是否可以保存
    if (copyNow.ruleConditionDTO && !!copyNow.ruleConditionDTO.ruleConditionDTOList.length) {
      if (saveAble) {
        saveAble = (workflowUtil.handleVerify(copyNow.ruleConditionDTO, copyNow, true)).isValid
      }
    }
    if (saveAble) {
      if (copyNow.remark === '' || !copyNow.remark) {
        copyNow.remark = copyNow.remark + copyNow.priority;
      }

      this.props.onSave(copyNow);
    }
  };

  //type === 'long' || type === 'double' || type === 'date'时，修改值
  handleRangeChange = (value, condition, isLeftValue) => {
    let { nowNode }= this.state;
    let getCurrentPart = (conditionOID, items) => {
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          item.valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
          let list = item.valueDetail.list || [{}, {}];
          list[isLeftValue ? 0 : 1].value = value;
          list && list.map((listItem, listIndex) => {
            if (!listItem.value && !Number(listItem.symbol)) {
              list[listIndex].value = null;
              list[listIndex].symbol = null;
            }
          });
          item.valueDetail.list = list;
        } else if (item.ruleConditionDTOList) {
          item.valueDetail = getCurrentPart(conditionOID, item.ruleConditionDTOList);
        }
      }
    };
    getCurrentPart(condition.conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({ nowNode })
  };


  //修改范围值的运算符
  handleRangeSymbolChange = (condition, symbol, isLeftValue) => {
    let { nowNode }= this.state;
    let getCurrentPart = (conditionOID, items) => {
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          item.valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
          let list = item.valueDetail.list || [{}, {}];
          list[isLeftValue ? 0 : 1].symbol = symbol;
          list && list.map((listItem, listIndex) => {
            if (!listItem.value && !Number(listItem.symbol)) {
              list[listIndex].value = null;
              list[listIndex].symbol = null;
            }
          });
          item.valueDetail.list = list;
        } else if (item.ruleConditionDTOList) {
          item.valueDetail = getCurrentPart(conditionOID, item.ruleConditionDTOList);
        }
      }
    };
    getCurrentPart(condition.conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({ nowNode })
  };

  handleSymbolChange = (condition, value) => {
    condition.symbol = Number(value);
    this.setState({ nowNode: this.state.nowNode })
  };

  handleTextValueChange = (condition, valueIndex, e) => {
    condition.valueDetail = workflowUtil.getStringJsonToObject(condition.valueDetail)
    let valueDetail = condition.valueDetail;
    let value = valueDetail && (valueDetail.value || []);
    value[0] = e.target.value;
    valueDetail.value = value;
    this.setState({ nowNode: this.state.nowNode })
  };

  getSymbloRender(condition, position = 'left') {
    let { symbolsType }= this.state;
    let type = workflowService.checkNewRemarkType(condition.remark);
    let RuleList = workflowUtil.getSymbolsTypeList(symbolsType);
    switch(type) {
      case 'text':
        return (
          <Select className="symblo-select"
                  onChange={symbol => {this.handleSymbolChange(condition, symbol)}}
                  value={String(condition.symbol)} size="small">
            {((condition.remark === 'default_user_work_number' || condition.remark === 'default_user_position' ) ?
              RuleList['haveRuleList'] :
              RuleList['containRuleList']).map(symbolsItem => {
              return <Option key={symbolsItem.key}>{symbolsItem.name}</Option>
            })}
          </Select>
        )
        break;
      case 'long':
      case 'double':
      case 'date':
      case 'combo': {
        //默认操作符 <= <
        condition.valueDetail = workflowUtil.getStringJsonToObject(condition.valueDetail);
        condition.valueDetail.list = condition.valueDetail.list || [{
            "value": null,
            "symbol": "9002"
          }, {
            "value": null,
            "symbol": "9003"
          }];
        let leftCondition = condition.valueDetail.list[0];
        let rightCondition = condition.valueDetail.list[1];
        if (position === 'left') {
          return <Select className="symblo-select" size="small" value={leftCondition.symbol || '0'}
                         onChange={symbol => {this.handleRangeSymbolChange(condition, symbol, true)}}>
            {RuleList['moreThanRuleList'].map(symbolsItem => {
              return <Option key={symbolsItem.key}>{symbolsItem.name}</Option>
            })}
          </Select>
        } else {
          return <Select className="symblo-select" size="small" value={rightCondition.symbol || '0'}
                         onChange={symbol => {this.handleRangeSymbolChange(condition, symbol, false)}}>
            {RuleList['lessThanAndEqualRuleList'].map(symbolsItem => {
              return <Option key={symbolsItem.key}>{symbolsItem.name}</Option>
            })}
          </Select>
        }
      }
        break;
      case 'selector':
      case 'custList': {
        let optionList = RuleList['inRuleList'];
        if (condition.remark === 'default_department_path' || condition.remark === 'custom_form_department_path') {
          optionList = RuleList['containRuleList'];
        }
        return <Select className="symblo-select" size="small"
                       value={String(condition.symbol)}
                       onChange={symbol => {this.handleSymbolChange(condition, symbol)}}>
          {optionList.map(symbolsItem => {
            return <Option key={symbolsItem.key}>{symbolsItem.name}</Option>
          })}
        </Select>
      }
        break;
      case 'boolean': {
        return <Select style={{ width: 150 }}
                       onChange={symbol => {this.handleSymbolChange(condition, symbol)}}
                       className="symblo-select" value={String(condition.symbol)} size="small">
          {RuleList['booleanRuleList'].map(symbolsItem => {
            return <Option key={symbolsItem.key}>{symbolsItem.name}</Option>
          })}
        </Select>
      }
        break;
    }
  }

  deleteValues = (condition, oid) => {
    let { nowNode }= this.state;
    let getCurrentPart = (conditionOID, items) => {
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          item.valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
          item.valueDetail.valueOIDs.splice(item.valueDetail.valueOIDs.indexOf(oid), 1);
          item.valueDetail.value.splice(item.valueDetail.value.indexOf(oid), 1);
        } else if (item.ruleConditionDTOList) {
          item.valueDetail = getCurrentPart(conditionOID, item.ruleConditionDTOList);
        }
      }
    };
    getCurrentPart(condition.conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({ nowNode });
  };

//custList类型存值
  handleListData = (values) => {
    let { nowNode, conditionOID, listSearcherParams }= this.state;
    let { valueKey, labelKey } = listSearcherParams;
    let oid = [];
    let companyValue = [];
    let showValue = {}; //用于编辑状态下显示成本中心值，避免请求接口去获取显示值
    values.result.map(item => {
      oid.push(item[valueKey]);
      companyValue.push({ [valueKey]: item[valueKey] });
      showValue[item[valueKey]] = item[labelKey]
    });
    let getCurrentPart = (conditionOID, items) => {
      let valueDetail;
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          let valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
          valueDetail.valueOIDs = oid;
          valueDetail.value = oid;
          item.showValue = showValue;
          item.valueDetail = valueDetail;
          if (item.remark === 'default_department_role') {
            // item.fieldContent = JSON.stringify(values.result);
          }
        } else if (item.ruleConditionDTOList) {
          valueDetail = getCurrentPart(conditionOID, item.ruleConditionDTOList);
        }
      }
    };
    getCurrentPart(conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({
      nowNode,
      listSearcherVisible: false,
      listSelectorVisible: false,
      expenseTypeVisible: false,
    })
  };

//添加值列表
  handleAddSelectorData = () => {
    let { nowNode, conditionOID }= this.state;
    let getCurrentPart = (conditionOID, items) => {
      let valueDetail;
      let valueOIDs = [];
      let values = [];
      let showValue = {}; //用于编辑状态下值列表的值
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
          this.state.selectorNowData.map(type => {
            this.state.selectorData.map((value) => {
              if (item.remark === 'default_department_level' || item.remark === 'default_credit_level' || item.remark === 'custom_form_department_level') {
                //前端值列表
                if (String(value.id) === String(type)) {
                  valueOIDs.push(type);
                  values.push(type);
                  showValue[value.id + ''] = value.name;
                }
              } else {
                //后端值列表
                if (value.customEnumerationItemOID === type) {
                  valueOIDs.push(type);
                  values.push(value.value);
                  showValue[value.customEnumerationItemOID] = value.messageKey
                }
                if (String(value.id) === String(type)) {
                  valueOIDs.push(type);
                  values.push(type);
                  showValue[value.id + ''] = value.name;
                }
              }
            })
          });
          valueDetail.valueOIDs = valueOIDs;
          valueDetail.value = values;
          item.valueDetail = valueDetail;
          item.showValue = showValue;
          break;
        } else if (item.ruleConditionDTOList) {
          valueDetail = getCurrentPart(conditionOID, item.ruleConditionDTOList);
        }
      }
    };
    getCurrentPart(conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({ selectorVisible: false, nowNode })
  };

  setSelectorValue = (item, res) => {
    this.setState({
      selectorLoading: false,
      selectorNowData: workflowUtil.getStringJsonToObject(item.valueDetail).valueOIDs || [],
      selectorData: res
    });
  };

//获取前端生成的值列表
  getDefaultSelector = (item) => {
    let seletorData = {
      'default_credit_level': Array.apply(null, { length: 26 }).map((item, index) =>
        ({ id: String.fromCharCode(index + 65), name: String.fromCharCode(index + 65) })),//信用等级
      'default_department_level': Array.apply(null, { length: 10 }).map((item, index) =>
        ({ id: String(index + 1), name: chnNumChar[index] })),//部门层级
      'custom_form_department_level': Array.apply(null, { length: 10 }).map((item, index) =>
        ({ id: String(index + 1), name: chnNumChar[index] })),//部门层级
      'default_auto_audit_result':  //自动审核结果
        [
          { name: messages('setting.key2240')/*未自动审核*/, id: 0 },
          { name: messages('common.pass')/*通过*/, id: 1 },
          { name: messages('setting.key2241')/*不通过*/, id: 2 },
        ],
      'default_stroke_type': itineraryTypes,
    };
    this.setState({
      selectorLoading: true, selectorVisible: true, conditionOID: item.conditionOID
    }, () => {
      this.setSelectorValue(item, seletorData[item.remark]);
    });
  };
//获取全部部门扩展字段值列表
  getDepartmentExtend = (item) => {
    item.conditionOID = item.conditionOID || workflowUtil.getRandomUUID();
    this.setState({
      selectorLoading: true, selectorVisible: true, conditionOID: item.conditionOID
    }, () => {
      workflowService.getValueListInfo(item.customEnumerationOID)
        .then((res) => {
          this.setSelectorValue(item, res.data.values);
        })
    });
  };

  getControlLabel = (item, type) => {
    item.conditionOID = item.conditionOID || workflowUtil.getRandomUUID();
    this.setState({
      selectorLoading: true, selectorVisible: true, conditionOID: item.conditionOID
    }, () => {
      workflowService.getInvoiceLabels(type)
        .then(res => {
          this.setSelectorValue(item, res.data);
        })
    })
  };
//系统值列表
  getTypeValues = (item, sq, index) => {
    let params = {
      ruleIndex: index,
      level: sq,
      systemCustomEnumerationType: item.fieldContent
    };
    item.conditionOID = item.conditionOID || workflowUtil.getRandomUUID();
    this.setState({
      selectorLoading: true,
      selectorVisible: true,
      level: sq,
      ruleIndex: index,
      conditionOID: item.conditionOID
    })
    workflowService.getBatchTypeList(params)
      .then((res) => {
        this.setSelectorValue(item, res.data.values);
      })

  };

//type custList listselector&listsearch组件赋值
  addCustListValue = (condition) => {
    let isDepartment = condition.remark === 'select_department' || condition.remark === 'default_user_department';
    let isDepartmentPath = condition.remark === 'default_department_path' || condition.remark === 'custom_form_department_path';
    const { company } = this.props;
    let { listSearcherParams, expenseTypeVisible } = this.state;
    listSearcherParams = {};
    let visble = 'listSelectorVisible';
    let selectedData = [];
    let expenseTypeValue = [];
    let listData = workflowUtil.getStringJsonToObject(condition.valueDetail).valueOIDs || [];
    let showValue = condition.showValue || {};
    switch(condition.remark) {
      case 'select_company':
      case 'default_applicant_company': {//公司&表单默认公司
        listData.map(oids => {
          selectedData.push({ companyOID: oids, name: showValue[oids] })
        });
        listSearcherParams.type = 'available_company';
        listSearcherParams.valueKey = 'companyOID';
        listSearcherParams.labelKey = 'name';
        listSearcherParams.selectedData = selectedData;
      }
        break;
      case 'select_corporation_entity':
      case 'default_corporation_entity': {
        listData.map(oids => {
          selectedData.push({ companyReceiptedOID: oids, companyName: showValue[oids] })
        });
        listSearcherParams.type = 'corporation_entity_all';
        listSearcherParams.valueKey = 'companyReceiptedOID';
        listSearcherParams.labelKey = 'companyName';
        listSearcherParams.selectedData = selectedData;
      }
        break;
      case 'default_user_direct_leadership'://直属领导
      case 'default_user_applicant'://申请人
        listData.map(oids => {
          selectedData.push({ userOID: oids, fullName: showValue[oids] })
        });
        listSearcherParams.type = 'user_all';
        listSearcherParams.valueKey = 'userOID';
        listSearcherParams.labelKey = 'fullName';
        listSearcherParams.selectedData = selectedData;
        break;
      case 'default_loan_type'://借款类型
        listData.map(oids => {
          selectedData.push({ id: oids, description: showValue[oids] })
        });
        listSearcherParams.valueKey = 'id';
        listSearcherParams.labelKey = 'description';
        listSearcherParams.selectedData = selectedData;
        listSearcherParams.extraParams = {
          setOfBookId: this.props.tenantMode ? this.props.setOfBooksId : this.props.company.setOfBooksId
        };
        listSearcherParams.selectorItem = {
          title: messages('components.key692')/*选择借款类型*/,
          url: `${config.payUrl}/api/cash/transaction/classes/queryBySetOfBookId/${this.props.tenantMode ?
            this.props.setOfBooksId : this.props.company.setOfBooksId}`,
          searchForm: [
            {
              type: 'input',
              id: 'classCode',
              label: messages('components.key693')/*借款类型代码*/
            },
            {
              type: 'input',
              id: 'description',
              label: messages('components.key694')/*借款类型*/
            }
          ],
          columns: [
            {
              title: messages('components.key693')/*借款类型代码*/,
              dataIndex: 'classCode',
              render: value => {
                return <Popover placement="topLeft" content={value} overlayStyle={{ maxWidth: 500 }}>{value}</Popover>
              }
            },
            {
              title: messages('components.key694')/*借款类型*/,
              dataIndex: 'description',
              render: value => {
                return <Popover placement="topLeft" content={value} overlayStyle={{ maxWidth: 500 }}>{value}</Popover>
              }
            }
          ],
          key: 'id'
        };
        break;
      case 'default_department_group'://部门组
      case 'custom_form_department_group':
        listData.map(oids => {
          selectedData.push({ deptGroupCode: oids, name: showValue[oids] })
        });
        listSearcherParams.type = 'department_group';
        listSearcherParams.valueKey = 'deptGroupCode';
        listSearcherParams.labelKey = 'name';
        listSearcherParams.selectedData = selectedData;
        break;
      //seacrcher控件
      case 'default_department_role'://部门角色
      case 'custom_form_department_role':
        listData.map(oids => {
          selectedData.push({ positionCode: oids, positionName: showValue[oids] })
        });
        visble = 'listSearcherVisible';
        listSearcherParams.type = 'department_role';
        listSearcherParams.valueKey = 'positionCode';
        listSearcherParams.filterRule = item => item.enabled;
        listSearcherParams.labelKey = 'positionName';
        listSearcherParams.selectedData = selectedData;
        break;
      case 'currency_code':
        listData.map(oids => {
          selectedData.push({ currencyCode: oids, fullName: showValue[oids] })
        });
        visble = 'listSearcherVisible';
        listSearcherParams.type = 'currency';
        listSearcherParams.valueKey = 'currencyCode';
        listSearcherParams.showDetail = true;
        listSearcherParams.labelKey = 'fullName';
        listSearcherParams.selectedData = selectedData;
        listSearcherParams.extraParams = { companyOID: company.companyOID };
        break;
      case 'select_cost_center'://成本中心
        listData.map(oids => {
          selectedData.push({ costCenterItemOID: oids, name: showValue[oids] })
        });
        listSearcherParams.selectorItem = {
          title: messages('components.key68'/*成本中心*/),//成本中心
          url: `${config.baseUrl}/api/cost/center/items/${condition.customEnumerationOID}/all`,
          //成本中心名称"成本中心项名称／经理／编号
          searchForm: [
            {
              type: 'input',
              id: 'keyword',
              label: `${messages('components.key69'/*成本中心名称*/)}/${messages('components.key71'/*经理*/)}/${messages('components.key73'/*编号*/)}`
            }
          ],
          columns: [
            {
              title: messages('components.key72'/*成本中心代码*/),//成本中心代码
              dataIndex: 'code'
            },
            {
              title: messages('components.key69'/*成本中心名称*/),//成本中心名称
              dataIndex: 'name',
              render: value => {
                return <Popover placement="topLeft" content={value} overlayStyle={{ maxWidth: 500 }}>{value}</Popover>
              }
            }
          ],
          key: 'costCenterItemOID'
        };
        listSearcherParams.valueKey = 'costCenterItemOID';
        listSearcherParams.labelKey = 'name';
        listSearcherParams.selectedData = selectedData;
        break;
      case 'default_expense_type'://费用类型
        visble = 'expenseTypeVisible';
        listData.map(oids => {
          expenseTypeValue.push({ expenseTypeOID: oids, name: showValue[oids] })
        });

        // expenseTypeValue
        // expenseTypeVisible
        break;
      case 'default_user_group'://
        listData.map(oids => {
          selectedData.push({ userGroupOID: oids, name: showValue[oids] })
        });
        listSearcherParams.type = 'user_group';
        listSearcherParams.valueKey = 'userGroupOID';
        listSearcherParams.labelKey = 'name';
        listSearcherParams.selectedData = selectedData;
    }
    this.setState({
      singleExpense: false,
      expenseTypeValue,
      conditionOID: condition.conditionOID || workflowUtil.getRandomUUID(),
      listSearcherParams,
      [visble]: !(isDepartmentPath || isDepartment),
      valueKey: listSearcherParams['valueKey'],
      labelKey: listSearcherParams['labelKey'],
    })

  };

  handleExpenseAmountType = (item, index, depth) => {
    let { expenseTypeValue } = this.state;
    let visble = 'expenseTypeVisible';
    if (item.showValue) {
      expenseTypeValue.expenseTypeOID = item.field;
      expenseTypeValue.name = item.showValue;
    } else {
      expenseTypeValue = {};
    }
    this.setState({
      expenseTypeValue,
      [visble]: true,
      singleExpense: true,
      ruleDepth: depth,
      ruleIndex: index,
      conditionOID: item.conditionOID
    });
  };

//添加部门路径/部门
  handleAddDepPath = (values, condition) => {
    let valueOIDs = [];
    let value = [];
    let showValue = {}; //用于编辑状态下显示部门，避免请求接口去获取显示值
    values.map(item => {
      valueOIDs.push(item.departmentOID);
      if (condition.remark === 'custom_form_department_path' || condition.remark === 'default_department_path') {
        value.push(item.path);
        showValue[item.path] = item.path;
      } else {
        value.push(item.departmentOID);
        showValue[item.departmentOID] = item.name
      }
    });
    let valueDetail = workflowUtil.getStringJsonToObject(condition.valueDetail);
    if (valueDetail.value && valueDetail.value.length) {
      valueDetail.valueOIDs = [];
      valueDetail.value = [];
      valueOIDs.map((oid, oidIndex) => {
        valueDetail.valueOIDs.push(oid);
        valueDetail.value.push(oid);
      });
      if (condition.remark === 'custom_form_department_path' || condition.remark === 'default_department_path') {
        valueDetail.value = [];
        value.map(val => {
          valueDetail.value.push(val);
        });
      }
    }
    valueDetail.valueOIDs = valueOIDs;
    valueDetail.value = value;
    condition.showValue = showValue;
    condition.valueDetail = valueDetail;
    this.setState({ nowNode: this.state.nowNode })
  };

  addSelectorValue = (condition) => {
    this.setState({}, () => {
      switch(condition.remark) {
        case 'default_user_post'://默认条件中的自定义列表
        case 'default_user_category':
        case 'default_user_sex':
        case 'default_user_level':
          this.getTypeValues(condition);
          break;
        case  'default_user_department_extend'://扩展字段值列表
        case 'cust_list':
        case 'custom_form_department_extend':
          this.getDepartmentExtend(condition)
          break;
        case 'control_beyound_label'://单据标签
          this.getControlLabel(condition, 1);
          break;
        case 'control_beyound_expense_label'://费用标签
          this.getControlLabel(condition, 2);
          break;
        //前端数据值列表
        case 'custom_form_department_level':
        case 'default_credit_level':
        case 'default_department_level':
        case 'default_auto_audit_result':
        case 'default_stroke_type':
          this.getDefaultSelector(condition);
      }
    });

  };

  //添加费用类型
  handleAddExpenseType = () => {
    let { nowNode, conditionOID } = this.state;
    let getCurrentPart = (conditionOID, items) => {
      let oid = [];
      let valueDetail;
      let showValue = {}; //用于编辑状态下显示成本中心值，避免请求接口去获取显示值
      if (!this.state.singleExpense) {
        this.state.expenseTypeValue.map(item => {
          oid.push(item.expenseTypeOID);
          showValue[item.expenseTypeOID] = item.name;
        });
      }
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
          if (item.remark === 'default_expense_type' && item.conditionOID === conditionOID) {
            let valueDetail = workflowUtil.getStringJsonToObject(item.valueDetail);
            valueDetail.value = oid;
            valueDetail.valueOIDs = oid;
            item.valueDetail = valueDetail;
            item.showValue = showValue
          }
          if ((item.remark === 'default_each_one_expense_type_amount'
            || item.remark === 'default_expense_type_amount'
            || item.remark === 'default_average_amount') && item.conditionOID === conditionOID) {
            item.field = this.state.expenseTypeValue.expenseTypeOID;
            item.showValue = this.state.expenseTypeValue.name;
          }
          break;
        } else if (item.ruleConditionDTOList) {
          valueDetail = getCurrentPart(conditionOID, item.ruleConditionDTOList);
        }
      }
    };
    getCurrentPart(conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({ nowNode, expenseTypeVisible: false })
  };

  /**
   * 根据条件的remark分类 不同type条件在页面的样式
   * getSymbloRender 获取不同类型的操作符
   * type : text combo custList selector long double boolean date
   * */
  conditionRender = (condition) => {
    let type = workflowService.checkNewRemarkType(condition.remark);
    let isDepartment = condition.remark === 'select_department' || condition.remark === 'default_user_department';
    let isDepartmentPath = condition.remark === 'default_department_path' || condition.remark === 'custom_form_department_path';
    let { listSearcherParams } = this.state;
    let depath = {};
    if (isDepartmentPath || isDepartment) {
      depath[condition.conditionOID] = [];
      let valueDetail = workflowUtil.getStringJsonToObject(condition.valueDetail);
      valueDetail.valueOIDs && !!valueDetail.valueOIDs.length && valueDetail.valueOIDs.forEach((val, index) => {
        let tem = {
          departmentOID: isDepartmentPath ? valueDetail.valueOIDs[index] : val,
          path: isDepartmentPath ? valueDetail.value[index] : null,
          name: isDepartmentPath ? valueDetail.value[index] : condition.showValue[val],
        };
        depath[condition.conditionOID].push(tem);
      });
      listSearcherParams.selectedDeps = depath[condition.conditionOID];
    }
    let style = {};
    if (condition.warning) {
      style = { color: '#FF3737' }
    }
    switch(type) {
      case 'text'://文本类型
      {
        let valueList = workflowUtil.getStringJsonToObject(condition.valueDetail).value || [''];
        return <span>
          <span className="left-name" style={style}>
            <Popover style={{ maxWidth: 200 }} content={condition.name}>{condition.name}</Popover>
          </span>
          <Col span={4}>{this.getSymbloRender(condition)}</Col>
          <Col span={14}>{valueList.map((value, valueIndex) => {
            return (
              <Input key={valueIndex} size="small" value={value}
                     style={{ width: 200 }}
                     onChange={e => this.handleTextValueChange(condition, valueIndex, e,)}/>
            )
          })}
          </Col>
          </span>
      }
        break;
      case 'combo'://费用类型金额等组合类型
      case 'long'://整数类型
      case 'double': {
        let name = messages('setting.key1203')/*金额*/;
        switch (condition.remark){
          case 'default_each_one_expense_type_amount':
           name = messages('setting.key2012')/*单行金额*/ ;
           break;
          case 'default_expense_type_amount':
            name = messages('setting.key1203')/*金额*/;
            break;
          case 'default_average_amount':
            name = messages('setting.key2252')/*人均金额*/ ;
            break;
        }
        //默认操作符 <= <
        let leftCondition = ( workflowUtil.getStringJsonToObject(condition.valueDetail).list || [])[0] || {
            "value": null,
            "symbol": "9002"
          };
        let rightCondition = (workflowUtil.getStringJsonToObject(condition.valueDetail).list || [])[1] || {
            "value": null,
            "symbol": "9003"
          };
        return <span>
            <Col span={4}>
                 <InputNumber precision={type === 'long' ? 0 : 2} min={0.00} max={9999999999.99} size="small"
                              value={leftCondition.value}
                              onChange={value => this.handleRangeChange(value, condition, true,)}/>
            </Col>
          {/*操作符*/}
          <Col span={4}>{this.getSymbloRender(condition, 'left')}</Col>
          {type === 'combo' && <Col span={4}>
            <div className="select-div"
                 onClick={() => this.handleExpenseAmountType(condition)}>{condition.showValue || '*请选择费用类型'}</div>
          </Col>}
          <span className="left-name" style={style}>{type === 'combo' ? name : condition.name}</span>
          <Col span={4}>{this.getSymbloRender(condition, 'right')}</Col>
          <Col span={4}>
                 <InputNumber precision={type === 'long' ? 0 : 2} min={0.00} max={9999999999.99} size="small"
                              value={rightCondition.value}
                              onChange={value => this.handleRangeChange(value, condition, false)}/>
            </Col>
          </span>
      }
        break;
      case 'selector'://值列表类型
      case 'custList': {
        let name = '',
          customForm = ['custom_form_department_extend', 'custom_form_department_path', 'select_department',
            'custom_form_department_level', 'custom_form_department_role', 'custom_form_department_group'],
          defaultMessage = ['default_user_department_extend', 'default_user_department', 'default_department_path',
            'default_department_level', 'default_department_role', 'default_department_group','default_user_group'];
        if (customForm.indexOf(condition.remark) !== -1) {
          name = messages('setting.key1930', { arg1: condition.name })/*【表单】{arg1}*/;
        } else if (defaultMessage.indexOf(condition.remark) !== -1) {
          name = messages('setting.key1931', { arg1: condition.name })/*【申请人】{arg1}*/;
        } else {
          name = condition.name
        }
        let isShowAddBtn = !(String(condition.symbol) === '9015' || String(condition.symbol) === '9016');
        let valueList = workflowUtil.getStringJsonToObject(condition.valueDetail).valueOIDs || [];
        if (!isShowAddBtn) {
          condition.valueDetail = null;
        }
        if (isDepartmentPath) {
          valueList = workflowUtil.getStringJsonToObject(condition.valueDetail).value || [];
        }
        return <span>
          <span className="left-name" style={style}>
            <Popover style={{ maxWidth: 200 }} content={name}>{name}</Popover>
          </span>
          {/*操作符*/}
          <Col span={4}>{this.getSymbloRender(condition)}</Col>
          {isShowAddBtn && <Col span={13}>
            <div className="tag-select">{valueList.map((value, valueIndex) => {
              return (
                <Tag
                  key={value}
                  closable
                  onClose={(e) => this.deleteValues(condition, value)}>
                  {condition.showValue && condition.showValue[value]}
                </Tag>
              )
            })}
              <span className="add-condition"
                    onClick={() => type === 'selector' ? this.addSelectorValue(condition) :
                      this.addCustListValue(condition)}>
                {(isDepartmentPath || isDepartment) ?
                  <SelectDepOrPerson renderButton={false}
                                     title={messages('common.add')}
                                     onlyDep={true}
                                     {...listSearcherParams}
                                     onConfirm={values => this.handleAddDepPath(values, condition)}/> : messages('common.add')/*添加*/}</span>
            </div>
          </Col>}
        </span>
      }
        break;
      case 'boolean'://布尔类型 选择值只有是否
      {
        let { symbolsType } = this.state;
        let name = '';
        if (condition.remark === 'judge_cost_center') {
          name = messages('setting.key1932', { arg1: condition.name })
          /*申请人={arg1}经理*/
        } else {
          name = condition.name
        }
        return <span>
          <span className="left-name" style={style}>
            <Popover style={{ maxWidth: 200 }} content={name}>{name}</Popover>
          </span>
          {/*操作符*/}
          <Col span={4}>{this.getSymbloRender(condition)}</Col>
          <Col span={13}/>
        </span>
      }
        break;
      case 'date':
        //日期类型
      {
        //默认操作符 <= <
        let leftCondition = ( workflowUtil.getStringJsonToObject(condition.valueDetail).list || [])[0] || {
            "value": null,
            "symbol": "9002"
          };
        let rightCondition = (workflowUtil.getStringJsonToObject(condition.valueDetail).list || [])[1] || {
            "value": null,
            "symbol": "9003"
          };
        return <span>
            <Col span={4}>
                      <DatePicker size="small" format="YYYY-MM-DD"
                                  defaultValue={leftCondition.value ? moment(leftCondition.value) : undefined}
                                  onChange={e => this.handleRangeChange(moment(e).format('YYYY-MM-DD'), condition, true,)}/>
            </Col>
          {/*操作符*/}
          <Col span={4}>{this.getSymbloRender(condition, 'left')}</Col>
          <span className="left-name" style={style}>
            <Popover style={{ maxWidth: 200 }} content={condition.name}>{condition.name}</Popover>
          </span>
           <Col span={4}>{this.getSymbloRender(condition, 'right')}</Col>
          <Col span={4}>
                        <DatePicker size="small" format="YYYY-MM-DD"
                                    defaultValue={rightCondition.value ? moment(rightCondition.value) : undefined}
                                    onChange={e => this.handleRangeChange(moment(e).format('YYYY-MM-DD'), condition, false,)}/>
            </Col>
          </span>
      }
        break;
    }
  };

  //最外层的切换满足不满足的Menu
  handleOuterVisible = () => {
    this.setState({ outerVisible: true, isAddGroup: false })
  };

  /**
   * 删除条件
   *type 条件组 还是条件
   **/
  handleDeleteCondition = (conditionOID) => {
    let { nowNode } = this.state;
    let getCurrentPart = (conditionOID, items) => {
      for(let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.conditionOID === conditionOID) {
          items.splice(i, 1);
          //删除条件
          break;
        } else if (item.ruleConditionDTOList) {
          getCurrentPart(conditionOID, item.ruleConditionDTOList)
        }
      }
    };
    getCurrentPart(conditionOID, nowNode.ruleConditionDTO.ruleConditionDTOList);
    this.setState({ nowNode })
  };

  handleCommonCondition = (flag, data) => {
    data.visible = flag;
    this.setState({ nowNode: this.state.nowNode })
  };

  handleAddCommonCondition = (values, data) => {
    data.visible = false;
    values.map(item => {
      item.type = 1
    });
    data.ruleConditionDTOList = data.ruleConditionDTOList.concat(values);
    this.setState({ nowNode: this.state.nowNode })
  };
  handleCommonMenuClick = (key, data) => {
    let { isAddGroup } = this.state;
    if (isAddGroup) {
      data.ruleConditionDTOList.push({
        symbol: Number(key.key),
        type: 2,
        conditionOID: workflowUtil.getRandomUUID(),//前端生成的唯一标示 不做存储
        ruleConditionDTOList: []
      });
    } else {
      data.symbol = Number(key.key);
    }
    this.setState({ nowNode: this.state.nowNode })
  };

  /**
   * 递归显示条件
   * @param data 条件对象
   * @params sq index
   *
   * function conditionRender 各种条件的分类处理
   * */
  recursiveCondition = (data, sq = null) => {
    let menu = (
      <Menu onClick={key => this.handleCommonMenuClick(key, data)}>
        <Menu.Item key="9020">{messages('setting.key1933')/*满足全部*/}</Menu.Item>
        <Menu.Item key="9021">{messages('setting.key1934')/*满足任一*/}</Menu.Item>
      </Menu>
    );
    return <div className=" condition-content">
      <NewAddApproveRuleModal visible={data.visible}
                              formFieldList={this.props.params.formFieldList}
                              onOk={values => this.handleAddCommonCondition(values, data)}
                              onCancel={() => {this.handleCommonCondition(false, data)}}/>
      <div className="relation">
        <Dropdown
          onClick={() => {this.setState({ isAddGroup: false })}}
          overlay={menu}
          onVisibleChange={() => this.handleOuterVisible()}>
          <a className={(data.symbol || 9020 ) === 9021 ? 'part-fill' : 'all-fill' }>
            {data.symbol === 9020 ? messages('setting.key1933')/*满足全部*/ : messages('setting.key1934')/*满足任一*/}
            <Icon type="down"/>
          </a>
        </Dropdown>
        {(sq || sq === 0) && <Popconfirm onConfirm={(e) => {
          e.stopPropagation();
          this.handleDeleteCondition(data.conditionOID)
        }}
                                         title={messages('setting.key1935')/*确认删除该条件*/}>
          <Icon className="delete-icon" type="delete"/>
        </Popconfirm>}
      </div>
      <div className={`condition-content ${data.symbol === 9021 ? 'part-fill-border' : 'full-fill-border' }`}>
        {!!data.ruleConditionDTOList.length && data.ruleConditionDTOList.map((item, index) => {
          let style = {};
          if (item.warning) {
            style = { color: '#FF3737' }
          }
          let indexSq = workflowUtil.getIndexArr(item.conditionOID, this.state.nowNode).join('.');
          return <div><Row className="condition-item">
            <span className={`left-tab ${sq}`} style={style}>{indexSq}:</span>
            {this.conditionRender(item)}
            {item.type === 1 && <Col className="delete-btn">
              <Popconfirm onConfirm={(e) => {
                e.stopPropagation();
                this.handleDeleteCondition(item.conditionOID)
              }}
                          title={messages('setting.key1935')/*确认删除该条件*/}>
                <Icon className="delete-icon" type="delete"/>
              </Popconfirm>

            </Col>}
            {item.ruleConditionDTOList && this.recursiveCondition(item, index)}
          </Row>
          </div>
        })}
        <span className="add-btn" onClick={() => this.handleCommonCondition(true, data)}>
            <Icon type="plus" className="icon-padding"/>{messages('setting.key1936')/*新增*/}
        </span>
        { workflowUtil.getIndexArr(data.conditionOID, this.state.nowNode).length < 1 &&
        <span className="add-btn">
            <Dropdown
              onVisibleChange={() => {this.setState({ isAddGroup: true })}}
              overlay={menu}>
              <a>
                 <Icon type="plus" className="icon-padding"/>{messages('setting.key1937')/*新增条件组*/}
                <Icon type="down"/>
              </a>
            </Dropdown>
          </span>}
      </div>
    </div>
  };

  render() {
    let { language }= this.props;
    const {
      basicInfo, loading, listSearcherVisible,
      expenseTypeValue, expenseTypeVisible, selectorLoading, selectorData, selectorNowData, selectorVisible,
      listSelectorVisible, listSearcherParams, nowNode, priority,
    } = this.state;
    let selfApprovalRule = basicInfo.selfApprovalRule;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
    return (
      <Form>
        <Collapse key="condition" bordered={false} defaultActiveKey={['baseInfo', 'conditionInfo']}
                  className="workflow-base-setting">
          <Panel header={messages('setting.key1371')/*基础信息*/} key="baseInfo">
            <FormItem key="remark" {...formItemLayout} label={messages('setting.key1372'/*节点名称*/)} colon={false}>
              <Input onChange={(e) => this.onChangeAttr(e.target.value, 'remark')} value={nowNode.remark} size="small"
                     placeholder={messages('common.please.enter')}
                     style={{ width: 200 }}
                     autoComplete="off"/>
            </FormItem>
            <FormItem key="priority" {...formItemLayout} label={messages('setting.key270')/*优先级*/} colon={false}>
              <Select style={{ width: 150 }}
                      value={priority}
                      onChange={ e => this.handleChangeLevel(e, 'priority')}
                      className="symblo-select" size="small">
                {Array(this.getConditionlength().length).fill().map((_, i) => i + 1).map(value => {
                  return <Option key={value}>{value}</Option>
                })}
              </Select>
            </FormItem>
          </Panel>
          <Panel header={messages('setting.key1938')/*条件设置*/} key="conditionInfo">
            {/*初始条件添加*/}
            {!loading && <div className="rule-condition-list">
              <div>
                <div className="condition-group">
                  {/*递归条件入口*/}
                  <div>
                    {this.state.nowNode &&
                    this.recursiveCondition(nowNode.ruleConditionDTO || {
                        symbol: 9020,
                        ruleConditionDTOList: [],
                        type: 2,
                      })}
                  </div>
                </div>
              </div>
            </div>}
          </Panel>

        </Collapse>
        <div className="slide-footer">
          <Button type="primary"
                  onClick={this.handleSave}
                  className="save-btn"
                  htmlType="submit">{messages("common.save")}</Button>
          <Button className="cancel-btn" onClick={this.onCancel}>{messages('setting.key1080')/*取消*/}</Button>
        </div>
        <Modal
          title={messages('common.please.select')}
          visible={selectorVisible}
          onOk={this.handleAddSelectorData}
          onCancel={() => {
            this.setState({
              selectorVisible: false
            })
          }}>
          <Spin spinning={selectorLoading}>
            {(selectorVisible) &&
            selectorData.length === 0 ?
              <div style={{
                minHeight: '80px',
                textAlign: "center",
                color: "gray"
              }}>{messages('setting.key1307'/*暂无数据*/)}</div> :
              <div style={{ minHeight: '80px', }} className="select-rule-modal-container">
                <TagSelect
                  value={selectorNowData}
                  onChange={value => {this.setState({ selectorNowData: value })}}>
                  {(selectorData || []).map(item => {
                    return <TagSelect.Option
                      value={item.customEnumerationItemOID || item.id}
                      key={item.customEnumerationItemOID || item.id}>{item.name || item.messageKey}</TagSelect.Option>
                  })
                  }
                </TagSelect>
              </div>}
          </Spin>
        </Modal>
        <ListSearcher visible={listSearcherVisible}
                      {...listSearcherParams}
                      onOk={this.handleListData}
                      onCancel={() => {this.setState({ listSearcherVisible: false })}}/>
        <ListSelector visible={listSelectorVisible}
                      {...listSearcherParams}
                      onOk={this.handleListData}
                      onCancel={() => this.setState({ listSelectorVisible: false })}
        />
        {/*特殊类型 费用类型相关*/}
        <Modal title={messages('setting.key1308'/*选择费用类型*/)}
               visible={expenseTypeVisible}
               width={620}
               bodyStyle={{ maxHeight: 'calc(100vh - 150px)', overflow: 'auto' }}
               onOk={this.handleAddExpenseType}
               onCancel={() => {this.setState({ expenseTypeVisible: false })}}>
          <ExpenseTypeSelector source="formV2"
                               single={this.state.singleExpense}
                               value={expenseTypeValue}
                               param={{
                                 formOID: this.props.params.formInfo.formOID,
                                 isALL: true,
                                 setOfBooksId: this.props.setOfBooksId,
                                 subsidyType: 99
                               }}
                               onSelect={values => this.setState({ expenseTypeValue: values })}/>
        </Modal>
      </Form>
    );
  }
}

WorkflowConditionSetting.PropTypes = {
  example: React.PropTypes.object.isRequired,
  componentKey: React.PropTypes.string.isRequired,
  close: React.PropTypes.string.func,
  onOpenAdditionModal: React.PropTypes.string.func,
  ruleRoutes: React.PropTypes.array,
  ruleApprovalNodes: React.PropTypes.array,
  setOfBooksId: React.PropTypes.string
};


function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language
  }
}

const WrappedWorkflowConditionSetting = Form.create()(WorkflowConditionSetting);

export default connect(mapStateToProps)(
  WrappedWorkflowConditionSetting
);
